﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Remoting.Messaging;
using System.Threading.Tasks;
using Google.Protobuf.Examples.AddressBook;

namespace testClient
{
    public class TestUDPClient
    {
        public UdpClient udpClient;

        public TestUDPClient()
        {
            udpClient = new UdpClient(4040);
        }


        MessageProcess messageProcess = new MessageProcess();

        private int curFrameId = 1;
        public void Send(string[] s)
        {
            Console.WriteLine("BeforeReceive");
           
            var dataSend = new Data()
            {
                Data_ = s[1], // s helloworld
            };

            var memStream = new MemoryStream();
            var co = new Google.Protobuf.CodedOutputStream(memStream);
            dataSend.WriteTo(co);
            co.Flush();

            var data2 = memStream.ToArray();
            var len = (UInt16)data2.Length;

            var byteArray = new byte[2 + 2 + 1 + len];
            var frameId = curFrameId++;
            if (curFrameId >= 256)
            {
                curFrameId = 1;
            }

            var blen = BitConverter.GetBytes(len);

            var typeId = (UInt16)Program.protoIds[dataSend.GetType()];

            var typeArr = BitConverter.GetBytes(typeId);

            byte fid = (byte)frameId;
            var frameArr = BitConverter.GetBytes(fid);

            //length  typeId frameId pbdata
            Array.Copy(blen, byteArray, 2);
            Array.Copy(typeArr, 0, byteArray, 2, 2);
            Array.Copy(frameArr, 0, byteArray, 4, 1);
            Array.Copy(data2, 0, byteArray, 5, len);

            //byteArray 2 长度  + len 数据
            //var stream = client.GetStream();

            var endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5050);

            try
            {
                //stream.Write(byteArray, 0, byteArray.Length);
                udpClient.Send(byteArray, byteArray.Length, endPoint);
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.ToString());
                return;
            }
        }

        public async Task Receive()
        {

            UdpReceiveResult result;
            try
            {
                //n = await stream.ReadAsync(buffer, 0, 1024);
                result = await udpClient.ReceiveAsync();

            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.ToString());
                return;
            }

           
            messageProcess.Process(result.Buffer, result.Buffer.Length);

            Console.WriteLine("Receive: " + messageProcess.msgData.ToString());
            //messageProcess.msgData
            //World.world.SyncBody(messageProcess.msgData);

        }

        public void Close()
        {
        }
    }
}

